package com.jeff.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.lang.reflect.Type;

/**
 * author：duff
 * version：1.0.0
 * date：2017/8/31
 * desc：
 */
public class JSONUtil {
    public static boolean isPrintException = true;

    private static Gson sGson;

    /**
     * get Gson.
     * @return Gson.
     */
    public static Gson getGson() {
        if (sGson == null) {
            sGson = newGson();
        }

        return sGson;
    }

    /**
     * new Gson.
     * @return Gson.
     */
    public static Gson newGson() {
        return new GsonBuilder().create();
    }

    /**
     * convert json String to Object.
     * @param jsonString json string
     * @param clazz Object class
     * @param <T> Object Class Type
     * @return Object
     */
    public static <T> T fromJsonStringThrowEx(String jsonString, Class<T> clazz) throws JsonSyntaxException {
        return getGson().fromJson(jsonString, clazz);
    }

    public static <T> T optFromJsonString(String jsonString, Class<T> clazz) {
        try {
            return getGson().fromJson(jsonString, clazz);
        } catch (Throwable var3) {
            var3.printStackTrace();
            return null;
        }
    }

    /**
     * convert json string to the Object of the specified Type.
     * @param json json string
     * @param typeOfT Type
     * @param <T> Type
     * @return Object of T
     */
    public static <T> T fromJsonStringThrowEx(String json, Type typeOfT) throws JsonSyntaxException {
        return getGson().fromJson(json, typeOfT);
    }

    public static <T> T optFromJsonString(String json, Type typeOfT) {
        try {
            return getGson().fromJson(json, typeOfT);
        } catch (JsonSyntaxException var3) {
            var3.printStackTrace();
            return null;
        }
    }

    public static JSONObject fromInputStreamThrowEx(InputStream inputStream) throws JSONException {
        return new JSONObject(StringUtil.fromInputStream(inputStream));
    }

    public static JSONObject optFromInputStream(InputStream inputStream) {
        try {
            return new JSONObject(StringUtil.fromInputStream(inputStream));
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * vonvert Object to json string.
     * @param object Object
     * @return json string.
     */
    public static String toJsonStringThrowEx(Object object) throws Exception  {
        return getGson().toJson(object);
    }

    public static String optToJsonString(Object object) {
        try {
            return getGson().toJson(object);
        } catch (Throwable var2) {
            var2.printStackTrace();
            return "";
        }
    }

}
